package com.ztgf.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.shopping.models.dto.shop.ShopInfoAuditDTO;
import com.ztgf.shopping.models.service.audit.IAuditService;
import com.ztgf.shopping.models.service.shop.IShopInfoAuditService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.sys.mapper.SysHomePageStatisticsMapper;
import com.ztgf.sys.models.bo.SysHomePageBO;
import com.ztgf.sys.models.service.ISysHomePageStatisticsService;
import com.ztgf.sys.models.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/*
 * @author chenyu.wang
 * @date 2020-08-07
 * @description 系统首页统计服务
 */
@DubboService
public class SysHomePageStatisticsServiceImpl implements ISysHomePageStatisticsService {

    @Autowired
    private SysHomePageStatisticsMapper sysHomePageStatisticsMapper;
    @DubboReference
    private IShopInfoAuditService iShopInfoAuditService;
    @DubboReference
    private ICommodityInfoService iCommodityInfoService;
    @DubboReference
    private IAuditService auditService;
    @DubboReference
    private IShopInfoService shopInfoService;

    private static final String strDateFormat = "yyyy-MM-dd";

    private static final SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

    @Override
    public SysHomePageStatisticsVO querySysHomeStatistice() {
        SysHomePageStatisticsVO vo = new SysHomePageStatisticsVO();
        vo.setToDayOrderNumberTotal(sysHomePageStatisticsMapper.querySysHomeOrderTotal());//今日订单总数
        vo.setToDaySalesTotal(sysHomePageStatisticsMapper.querySysHomeSales());//今日销售总额
        vo.setToDayCommissionTotal(sysHomePageStatisticsMapper.queryTotalCommissionToday());//今日佣金总额
        vo.setToDayNewCommodityTotal(sysHomePageStatisticsMapper.querySysHomeNewGoods());//今日新上架产品
        vo.setNewUserRegisterAudit(auditService.getNum(0));//新用户注册审核
        vo.setCommodityPushAudit(sysHomePageStatisticsMapper.queryCommodityPushAudit());//产品上传审核
        vo.setProxyApplicationAudit(sysHomePageStatisticsMapper.queryApplyCount());//代理申请审核
        vo.setOpenShopAudit(auditService.getNum1(1,5));//开店审核
        vo.setAfterSaleNum(sysHomePageStatisticsMapper.queryAfterSaleNum());//售后申请介入
        vo.setNewCommodityCategoryAudit(auditService.getNum(4));//新增产品类目审核
        vo.setQualificationChangeAudit(auditService.getNum(2));//资质变更审核
        vo.setComplaintsAndSuggestion(sysHomePageStatisticsMapper.queryComplaintsCount());//投诉与建议
        vo.setNewBrandAudit(auditService.getNum(3));//新增品牌审核
        vo.setPurchaseCommodityAudit(auditService.getNum(6));//询盘商品审核
        vo.setLogisticsAudit(auditService.getNum(7));//物流审核
        return vo;
    }

    @Override
    public SysHomePageOverviewVO querySysHomeOverview() {
        SysHomePageOverviewVO vo = new SysHomePageOverviewVO();
//        vo.setNotListed(this.forListing());//未上架商品
//        vo.setItHasBeenAddedTo(this.itHasBeenAddedTo());//已上架商品
        vo.setNotListed(iCommodityInfoService.getPublishCount(0));//未上架商品
        vo.setItHasBeenAddedTo(iCommodityInfoService.getPublishCount(1));//已上架商品
        vo.setTightInventory(sysHomePageStatisticsMapper.getA() + sysHomePageStatisticsMapper.getB());//库存紧张
//        vo.setAllProducts(this.allProducts());//全部商品
        vo.setAllProducts(iCommodityInfoService.getPublishCount(null));//全部商品
        vo.setAddedToday(sysHomePageStatisticsMapper.queryAllUserCount(ONE));//今日新增
        vo.setAddedYesterday(sysHomePageStatisticsMapper.queryAllUserCount(TWO));//昨日新增
        vo.setAddedThisMonth(sysHomePageStatisticsMapper.queryAllUserCount(THREE));//本月新增
        vo.setAllUsers(sysHomePageStatisticsMapper.queryAllUserNum());//全部用户
        vo.setNotSku(sysHomePageStatisticsMapper.getSkuNum(0) + sysHomePageStatisticsMapper.getComboSkuNum(0));// 未上架sku
        vo.setAlreadySku(sysHomePageStatisticsMapper.getSkuNum(1) + sysHomePageStatisticsMapper.getComboSkuNum(1));// 已上架sku
        vo.setAllSku(sysHomePageStatisticsMapper.getSkuNum(null) + sysHomePageStatisticsMapper.getComboSkuNum(null));// 全部sku
        return vo;
    }

    @Override
    public List<SysHomePageOrderNumVO> querySysHomePageOrderNum(SysHomePageBO bo) {
        if (bo.getType() != null) {
            if (bo.getType() == ONE) {
                List<SysHomePageOrderNumVO> list = new ArrayList<>();
                SysHomePageOrderNumVO vo = new SysHomePageOrderNumVO();
                vo.setOrderNum(sysHomePageStatisticsMapper.querySysHomeOrderTotal());//本日
                vo.setThisDate(sdf.format(new Date()));
                list.add(vo);
                return list;
            } else if (bo.getType() == TWO) {
                return sysHomePageStatisticsMapper.queryHomePageOrderNumOnWeek();//本周
            } else {
                return sysHomePageStatisticsMapper.queryHomePageOrderNumOnMonth();//本月
            }
        } else {
            if (StringUtils.isNotBlank(bo.getStartTime()) && StringUtils.isNotBlank(bo.getEndTime())) {
                List<SysHomePageOrderNumVO> autoList = new ArrayList<>();
                SysHomePageOrderNumVO vo = sysHomePageStatisticsMapper.queryHomePageAutoOrderNum(bo.getStartTime(), bo.getEndTime());//自定义时间段
                vo.setThisDate(bo.getStartTime() + "~" + bo.getEndTime());
                autoList.add(vo);
                return autoList;
            }
        }
        return null;
    }

    @Override
    public SysHomePageOrderCompareVO getSysHomePageOrderLeft() {
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(TWO);
        SysHomePageOrderCompareVO vo = new SysHomePageOrderCompareVO();
        //本周
        Integer thisWeek = sysHomePageStatisticsMapper.queryOnUpOrderNum(TWO);
        //本月
        Integer thisMonth = sysHomePageStatisticsMapper.queryOnUpOrderNum(ONE);
        //上周
        Integer lastWeek = sysHomePageStatisticsMapper.queryOnUpOrderNum(THREE);
        //上月
        Integer firstMonth = sysHomePageStatisticsMapper.queryOnUpOrderNum(FOUR);
        if (lastWeek == ZERO) {
            vo.setWeeklyComparison(percent.format(1.00));
        } else {
            int a = thisWeek - lastWeek;
            double weeklyComparison = (float) a / (float) lastWeek;
            vo.setWeeklyComparison(percent.format(weeklyComparison));
        }
        if (firstMonth == ZERO) {
            vo.setMonthComparison(percent.format(1.00));
        } else {
            int a = thisMonth - firstMonth;
            double monthComparison = (float) a / (float) firstMonth;
            vo.setMonthComparison(percent.format(monthComparison));
        }
        vo.setOrdersThisWeek(thisWeek);
        vo.setOrdersThisMonth(thisMonth);
        vo.setOrdersLastWeek(lastWeek);
        vo.setOrdersLastMonth(firstMonth);
        return vo;
    }

    @Override
    public List<SysHomePageSalesVO> querySysHomePageSalesPrice(SysHomePageBO bo) {
        if (bo.getType() != null) {
            if (bo.getType() == ONE) {
                List<SysHomePageSalesVO> list = new ArrayList<>();
                SysHomePageSalesVO vo = new SysHomePageSalesVO();
                vo.setSalesPrice(sysHomePageStatisticsMapper.querySysHomeSales());//本日
                vo.setThisDate(sdf.format(new Date()));
                list.add(vo);
                return list;
            } else if (bo.getType() == TWO) {
                return sysHomePageStatisticsMapper.queryHomePageSalesWeek();//本周
            } else {
                return sysHomePageStatisticsMapper.queryHomePageSalesMonth();//本月
            }
        } else {
            if (StringUtils.isNotBlank(bo.getStartTime()) && StringUtils.isNotBlank(bo.getEndTime())) {
                List<SysHomePageSalesVO> autoList = new ArrayList<>();
                SysHomePageSalesVO vo = sysHomePageStatisticsMapper.queryHomePageAutoSelas(bo.getStartTime(), bo.getEndTime());//自定义时间段
                vo.setThisDate(bo.getStartTime() + "~" + bo.getEndTime());
                autoList.add(vo);
                return autoList;
            }
        }
        return null;
    }

    @Override
    public SysHomePageSalesCompareVO getSysHomePageSalesLeft() {
        SysHomePageSalesCompareVO vo = new SysHomePageSalesCompareVO();
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(TWO);
        //本周
        BigDecimal thisWeek = sysHomePageStatisticsMapper.queryOnUpSelas(TWO).setScale(TWO, RoundingMode.HALF_UP);
        //本月
        BigDecimal thisMonth = sysHomePageStatisticsMapper.queryOnUpSelas(ONE).setScale(TWO, RoundingMode.HALF_UP);
        //上周
        BigDecimal lastWeek = sysHomePageStatisticsMapper.queryOnUpSelas(THREE).setScale(TWO, RoundingMode.HALF_UP);
        //上月
        BigDecimal firstMonth = sysHomePageStatisticsMapper.queryOnUpSelas(FOUR).setScale(TWO, RoundingMode.HALF_UP);
        if (lastWeek.compareTo(BigDecimal.ZERO) == ZERO && thisWeek.compareTo(BigDecimal.ZERO) ==1) {
            vo.setWeeklyComparison(percent.format(1.00));
        } else {
            BigDecimal subtract = thisWeek.subtract(lastWeek);
            if (subtract.compareTo(BigDecimal.ZERO) ==0){
                vo.setWeeklyComparison(percent.format(0.00));
            }else {
                    vo.setWeeklyComparison(percent.format(subtract.divide(lastWeek,TWO, BigDecimal.ROUND_HALF_UP)));
            }
        }

        if (firstMonth.compareTo(BigDecimal.ZERO) == ZERO && thisMonth.compareTo(BigDecimal.ZERO) ==1) {
            vo.setMonthComparison(percent.format(1.00));
        }else {
            BigDecimal subtract = thisMonth.subtract(firstMonth);

            if (subtract.compareTo(BigDecimal.ZERO) ==0){
                vo.setMonthComparison(percent.format(0.00));
            }else {
                vo.setMonthComparison(percent.format(subtract.divide(firstMonth,TWO, BigDecimal.ROUND_HALF_UP)));
            }
        }
        vo.setOrdersThisWeek(thisWeek);
        vo.setOrdersThisMonth(thisMonth);
        vo.setOrdersLastWeek(lastWeek);
        vo.setOrdersLastMonth(firstMonth);
        return vo;
    }
    @Override
    public List<SysHomePageSalesVO> querySysHomePageCommission(SysHomePageBO bo) {
        if (bo.getType() != null) {
            if (bo.getType() == ONE) {
                List<SysHomePageSalesVO> list = new ArrayList<>();
                SysHomePageSalesVO vo = new SysHomePageSalesVO();
                vo.setSalesPrice(sysHomePageStatisticsMapper.queryTotalCommissionToday());//本日
                vo.setThisDate(sdf.format(new Date()));
                list.add(vo);
                return list;
            } else if (bo.getType() == TWO) {
                return sysHomePageStatisticsMapper.querySysHomeCommissionWeek();//本周
            } else {
                return sysHomePageStatisticsMapper.querySysHomeCommissionMonth(); //本月
            }
        } else {
            if (StringUtils.isNotBlank(bo.getStartTime()) && StringUtils.isNotBlank(bo.getEndTime())) {
                List<SysHomePageSalesVO> autoList = new ArrayList<>();
                SysHomePageSalesVO vo = sysHomePageStatisticsMapper.queryHomePageAutoCommission(bo.getStartTime(), bo.getEndTime()); //自定义时间段
                vo.setThisDate(bo.getStartTime() + "~" + bo.getEndTime());
                autoList.add(vo);
                return autoList;
            }
        }
        return null;
    }

    @Override
    public SysHomePageSalesCompareVO getSysHomePageCommissionLeft() {
        SysHomePageSalesCompareVO vo = new SysHomePageSalesCompareVO();
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(TWO);
        //本周
        BigDecimal thisWeek = sysHomePageStatisticsMapper.queryOnUpCommission(TWO).setScale(TWO, RoundingMode.HALF_UP);
        //本月
        BigDecimal thisMonth = sysHomePageStatisticsMapper.queryOnUpCommission(ONE).setScale(TWO, RoundingMode.HALF_UP);
        //上周
        BigDecimal lastWeek = sysHomePageStatisticsMapper.queryOnUpCommission(THREE).setScale(TWO, RoundingMode.HALF_UP);
        //上月
        BigDecimal firstMonth = sysHomePageStatisticsMapper.queryOnUpCommission(FOUR).setScale(TWO, RoundingMode.HALF_UP);
        if (lastWeek.compareTo(BigDecimal.ZERO) == ZERO && thisWeek.compareTo(BigDecimal.ZERO) ==1) {
            vo.setWeeklyComparison(percent.format(1.00));
        } else {
            BigDecimal subtract = thisWeek.subtract(lastWeek);
            if (subtract.compareTo(BigDecimal.ZERO) ==0){
                vo.setWeeklyComparison(percent.format(0.00));
            }else {
                vo.setWeeklyComparison(percent.format(subtract.divide(lastWeek,TWO, BigDecimal.ROUND_HALF_UP)));
            }
        }

        if (firstMonth.compareTo(BigDecimal.ZERO) == ZERO && thisMonth.compareTo(BigDecimal.ZERO) ==1) {
            vo.setMonthComparison(percent.format(1.00));
        }else {
            BigDecimal subtract = thisMonth.subtract(firstMonth);

            if (subtract.compareTo(BigDecimal.ZERO) ==0){
                vo.setMonthComparison(percent.format(0.00));
            }else {
                vo.setMonthComparison(percent.format(subtract.divide(firstMonth,TWO, BigDecimal.ROUND_HALF_UP)));
            }
        }
        vo.setOrdersThisWeek(thisWeek);
        vo.setOrdersThisMonth(thisMonth);
        vo.setOrdersLastWeek(lastWeek);
        vo.setOrdersLastMonth(firstMonth);
        return vo;
    }

    /*
     * @description:未上架商品
     * @author: chenyu.wang
     * @date: 2020-08-08
     * @param:
     * @return:
     */
    private Integer forListing() {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("audit_status", 1);
        wrapper.eq("is_publish", 0);
        wrapper.eq("status", 0);
        List<CommodityInfoDTO> commodityInfoDTOS = iCommodityInfoService.selectList(wrapper);
        if (commodityInfoDTOS!=null && commodityInfoDTOS.size()>0){
            List<CommodityInfoDTO> commodityInfoDTO1 = new ArrayList<>();
            for (CommodityInfoDTO commodityInfoDTO : commodityInfoDTOS) {
                boolean b = shopInfoService.checkShopIsClose(commodityInfoDTO.getShopId());
                if (b){
                    commodityInfoDTO1.add(commodityInfoDTO);
                }
            }
            if (commodityInfoDTO1!=null && commodityInfoDTO1.size()>0){
                return commodityInfoDTO1.size();
            }
        }
        return 0;
    }

    /*
     * @description:已上架商品
     * @author: chenyu.wang
     * @date: 2020-08-08
     * @param:
     * @return:
     */
    private Integer itHasBeenAddedTo() {
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("audit_status", 1);
        wrapper.eq("is_publish", 1);
        wrapper.eq("status", 0);
        List<CommodityInfoDTO> commodityInfoDTOS = iCommodityInfoService.selectList(wrapper);
        if (commodityInfoDTOS!=null && commodityInfoDTOS.size()>0){
            List<CommodityInfoDTO> commodityInfoDTO1 = new ArrayList<>();
            for (CommodityInfoDTO commodityInfoDTO : commodityInfoDTOS) {
                boolean b = shopInfoService.checkShopIsClose(commodityInfoDTO.getShopId());
                if (b){
                    commodityInfoDTO1.add(commodityInfoDTO);
                }
            }
            if (commodityInfoDTO1!=null && commodityInfoDTO1.size()>0){
                return commodityInfoDTO1.size();
            }
        }
        return 0;
    }

    /*
     * @description:全部商品
     * @author: chenyu.wang
     * @date: 2020-08-08
     * @param:
     * @return:
     */
    private Integer allProducts() {
        return iCommodityInfoService.allProducts();
    }

    /*
     * @description:开店审核数量
     * @author: chenyu.wang
     * @date: 2020-09-01
     */
    private Integer queryOpenShopAuditCount() {
        Wrapper<ShopInfoAuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("type", ONE);
        wrapper.andNew().eq("status", ZERO).or().eq("status", FOUR);
        return iShopInfoAuditService.selectCount(wrapper);
    }

    /*
     * @description:新增品牌类目待审核数量
     * @author: chenyu.wang
     * @date: 2020-09-01
     */
    private Integer queryAddCategoryCount() {
        Wrapper<ShopInfoAuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("type", FOUR);//"审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目"
        //0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
        wrapper.eq("status", ZERO);
        return iShopInfoAuditService.selectCount(wrapper);
    }

    /*
     * @description:品牌新增待审核数量
     * @author: chenyu.wang
     * @date: 2020-09-01
     */
    private Integer queryAddBrandCount() {
        Wrapper<ShopInfoAuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("type", THREE);//"审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目"
        //0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
        wrapper.eq("status", ZERO);
        return iShopInfoAuditService.selectCount(wrapper);
    }

    /*
     * @description:资质变更审核数量
     * @author: chenyu.wang
     * @date: 2020-09-01
     */
    private Integer queryChangeCount() {
        Wrapper<ShopInfoAuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("type", TWO);//"审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目"
        //0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
        wrapper.eq("status", ZERO);
        return iShopInfoAuditService.selectCount(wrapper);
    }

    public List<SysLineChartVO> querySysHomePageOrderCount(String startTime, String endTime) {
        return sysHomePageStatisticsMapper.querySysHomePageOrderCount(startTime, endTime);
    }

    @Override
    public List<SysLineChartVO> querySysHomePageSaleCount(String startTime, String endTime) {
        return sysHomePageStatisticsMapper.querySysHomePageSaleCount(startTime, endTime);
    }

    @Override
    public List<SysLineChartVO> querySysHomePageDealPrice(String startTime, String endTime) {
        return sysHomePageStatisticsMapper.querySysHomePageDealPrice(startTime, endTime);
    }

    @Override
    public List<SysLineChartVO> querySysHomePageCommissionCount(String startTime, String endTime) {
        return sysHomePageStatisticsMapper.querySysHomePageCommissionCount(startTime, endTime);
    }

}
